package com.yx1996.bean.day03;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl extends JdbcDaoSupport implements UserDao{

    //可以在这里创建JdbcTemplate对象   然后通过连接池对象获得jt类在创建jt对象
    //还可以继承JdbcDaoSupport类   该父类提供了super.getJdbcTemplate()方法通过连接池对象直接获得jt对象
    /*private JdbcTemplate jt;*/

    @Override
    //保存用户
    public void save(User u) {

        String sql = "insert into user values(null,?)";
        super.getJdbcTemplate().update(sql,u.getName());

    }

    @Override
    //删除用户
    public void delete(Integer id) {

        String sql = "delete from user where id=?";
        super.getJdbcTemplate().update(sql,id);
    }

    @Override
    //更新用户
    public void update(User u) {

        String sql = "update user set name=? where id=?";
        super.getJdbcTemplate().update(sql,u.getName(),u.getId());
    }

    @Override
    //查找用户
    public User select(Integer id) {
        String sql = "select * from user where id=?";
        return super.getJdbcTemplate().queryForObject(sql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User u = new User();
                u.setId(resultSet.getInt("id"));
                u.setName(resultSet.getString("name"));
                return u;
            }
        },id);
    }

    @Override
    //获得用户总数
    public Integer getTotalCount() {
        String sql = "select count(*) from user";
        Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class);
        return count;
    }

    @Override
    //获得所有用户
    public List<User> getAll() {
        String sql = "select * from user";
        return super.getJdbcTemplate().query(sql,new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User u = new User();
                u.setId(resultSet.getInt("id"));
                u.setName(resultSet.getString("name"));
                return u;
            }
        });
    }



   /* public JdbcTemplate getJt() {
        return jt;
    }

    public void setJt(JdbcTemplate jt) {
        this.jt = jt;
    }*/
}
